package com.example.service.impl;

import com.example.common.ApiRestResponse;
import com.example.common.MD5;
import com.example.exception.ImoocMallException;
import com.example.exception.ImoocMallExceptionEnum;
import com.example.mall.model.dao.UserMapper;
import com.example.mall.model.pojo.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
//
    @Override
    public boolean CheckLoginRole(User user) {
      User result =   userMapper.selectByPrimaryKey(user.getId());

        return result.getRole().equals(2);
    }

    @Override
    public User getUser(String username) {

        return userMapper.selectByName(username);
    }
//注册用户
    @Override
    public void Register(String username, String password) {
        /**
         * 1.判断用户名是否存在
         * 2.添加到数据库
         */
        User result = userMapper.selectByName(username);
        if(result!=null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NAME_EXISTED);
        }
//        添加到数据库
        User user= new User();
//        加密密码
        MD5 md5=new MD5();
        user.setUsername(username);
        user.setPassword(md5.GetMD5(password));
        int count = userMapper.insertSelective(user);
        if(count==0){
            throw new ImoocMallException(ImoocMallExceptionEnum.ADD_FAILED);
        }
        throw new ImoocMallException(ImoocMallExceptionEnum.ADD_SUCCESS);
    }
//用户登录
    @Override
    public User Login(String username, String password) {
//        通过用户名从数据库中查看是否存在该用户
      User selectName =  userMapper.selectByName(username);
      if(selectName==null){
          throw new ImoocMallException(ImoocMallExceptionEnum.NO_EXIT_USER_NAME);
      }
            String psw=MD5.GetMD5(password);
        User user =  userMapper.SelectUser(username,psw);
        if(user==null){
            throw new ImoocMallException(ImoocMallExceptionEnum.ERROR_PWD);
        }
//        不返回密码
        return user;
    }
//更新签名
    @Override
    public void updataSignature(User user) {
        user.setPassword(MD5.GetMD5(user.getPassword()));
       int count =  userMapper.updateByPrimaryKeySelective(user);
       if(count>1){
           throw new ImoocMallException(ImoocMallExceptionEnum.UPDATE_SIGNATURE);
       }
    }

}
